#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <jsoncpp/json/json.h>
#include "Util.hpp"

//#define MYSELF 1

namespace Protocol_ns
{
#define SEP " "
#define SEP_LEN strlen(SEP)
#define HEADER_SEP "\r\n"
#define HEADER_LEN strlen("\r\n")
    // 以有效载荷的长度作为报头，\r\n为报文分隔符跟有效载荷组合的形式形成一个完整报头
    // 报头\r\n有效载荷\r\n -> "7"\r\n"10 + 20"\r\n

    std::string AddHeader(const std::string &str)
    {
        std::cout << "AddHeader 之前：\n" << str << std::endl;
        std::string s = std::to_string(str.size());
        s += HEADER_SEP;
        s += str;
        s += HEADER_SEP;
        std::cout << "AddHeader 之后：\n" << s << std::endl;
        return s;
    }

    std::string RemoveHeader(const std::string &str, int len)
    {
        std::cout << "RemoveHeader 之前：\n" << str << std::endl;
        std::string res = str.substr(str.size() - HEADER_LEN - len, len);
        std::cout << "RemoveHeader 之后：\n" << res << std::endl;
        return res;
    }

    int ReadPackage(int sock, std::string &inbuffer, std::string *package)
    {
        std::cout << "ReadPackage 之前 inbuffer：\n" << inbuffer << std::endl;
        char buffer[1024];
        ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
        if (s <= 0)
        {
            return -1;
        }

        buffer[s] = '\0';
        inbuffer += buffer;
        std::cout << "ReadPackage 之中 inbuffer：\n" << inbuffer << std::endl;
        //"7"\r\n"10 + 20"\r\n
        auto pos = inbuffer.find(HEADER_SEP);
        if (pos == std::string::npos)
        {
            return 0;
        }
        // 获取报头（有效载荷的长度）
        std::string lenStr = inbuffer.substr(0, pos);
        int len = Util::toInt(lenStr);
        // 预估整个报文的长度 "7"\r\n"10 + 20"\r\n
        int targetPackageLen = lenStr.size() + len + 2 * HEADER_LEN;
        if (inbuffer.size() < targetPackageLen) // 没有获取到一个完整报文
        {
            return 0;
        }
        *package = inbuffer.substr(0, targetPackageLen); // 将完整报文写入输出
        inbuffer.erase(0, targetPackageLen); // 清空输出缓冲区
        std::cout << "ReadPackage 之后 inbuffer：\n" << inbuffer << std::endl;
        return len;
    }
////////////////////////////////////////////////////////////////////////////////////////////////////
    class Request
    {
    public:
        Request() {}

        Request(int x, int y, char op) : _x(x), _y(y), _op(op)
        {
        }
        // struct -> string
        bool Serialize(std::string *outStr)
        {
            //"10 + 20"
            *outStr = "";
#ifdef MYSELF
            std::string x_string = std::to_string(_x);
            std::string y_string = std::to_string(_y);

            *outStr = x_string + SEP + _op + SEP + y_string;
            std::cout << "Request Serialize：\n" << *outStr << std::endl;
#else
            Json::Value root;//Vaule:一种万能对象,可以接收任意的kv类型
            root["x"] = _x;
            root["y"] = _y;
            root["op"] = _op;
            //Json::FastWriter writer;//writer：用来序列化的
            Json::StyledWriter writer;
            *outStr = writer.write(root);
#endif
            return true;
        }
        // string -> struct
        bool Deserialize(const std::string &inStr)
        {
#ifdef MYSELF
            // 10 + 20 -> [0] = 10, [1] = "+", [2] = 20
            std::vector<std::string> result;
            Util::StringSpilt(inStr, SEP, &result);

            if (result.size() != 3) 
            {
                return false;
            }
            if (result[1].size() != 1)
            {
                return false;
            }
            _x = Util::toInt(result[0]);
            _op = result[1][0];
            _y = Util::toInt(result[2]);
#else
            Json::Value root;
            Json::Reader reader;
            reader.parse(inStr, root);
            _x = root["x"].asInt();
            _op = root["op"].asInt();
            _y = root["y"].asInt();    
#endif
            Print();

            return true;
        }
        void Print()
        {
            std::cout << "_x： " << _x << std::endl;
            std::cout << "_y： " << _y << std::endl;
            std::cout << "_op： " << _op << std::endl;
        }
        ~Request() {}

    public:
        int _x;
        int _y;
        char _op;
    };

    class Response
    {
    public:
        Response() {}
        Response(int result, int code) : _result(result), _code(code)
        {
        }
        // struct -> string
        bool Serialize(std::string *outStr)
        {
            //_result _code
            *outStr = "";
#ifdef MYSELF
            std::string res_string = std::to_string(_result);
            std::string code_string = std::to_string(_code);

            *outStr = res_string + SEP + code_string;
            std::cout << "Request Serialize：\n" << *outStr << std::endl;
#else
            Json::Value root;//Vaule:一种万能对象,可以接收任意的kv类型
            root["result"] = _result;
            root["code"] = _code;
            //Json::FastWriter writer;//writer：用来序列化的
            Json::StyledWriter writer;
            *outStr = writer.write(root);
#endif
            Print();
            return true;
        }
        // string -> struct
        bool Deserialize(const std::string &inStr)
        {
#ifdef MYSELF
            // 10 0 10 1
            std::vector<std::string> result;
            Util::StringSpilt(inStr, SEP, &result);

            if (result.size() != 2)
            {
                return false;
            }
            _result = Util::toInt(result[0]);
            _code = Util::toInt(result[1]);
#else
            Json::Value root;
            Json::Reader reader;
            reader.parse(inStr, root);
            _result = root["result"].asInt();
            _code = root["code"].asInt();
#endif
            Print();
            return true;
        }
        void Print()
        {
            std::cout << "_result： " << _result << std::endl;
            std::cout << "_code： " << _code << std::endl;
        }
        ~Response() {}

    public:
        int _result;
        int _code;
    };

}